<template>
  <div id="app" class="cloth-order">
    <!-- 头部导航 -->
    <van-nav-bar ref="header" title="业务订单" left-arrow @click-left="comeBack" left-text="返回" >
      <template #right>
        <span v-permissions="'3489_3492'" @click="() => openChangeOrderWinFn()"><van-icon name="plus" size="20" /></span>
      </template>
    </van-nav-bar>
    <!-- 筛选 -->
    <van-search v-model="queryParam.customerName" placeholder="请输入关键字" @search="refreshOrderDataFn" />

    <div style="height:79.5vh;overflow: auto">
      <van-pull-refresh ref="vanPullRefresh4OrderRef" v-model="listRefreshing" success-text="刷新成功" @refresh="refreshOrderDataFn">
        <van-list ref="vanList4OrderRef" :finished="listFinished" finished-text="没有更多了" :immediate-check="false" @load="loadNextClothOrderDataFn">
          <div v-for="row in orderData" :key="row.id" class="order-card">
            <van-row gutter="20" type="flex" justify="space-between">
              <van-col class="col-customer">
                <span>{{ row.customerName }}({{row.id}})</span>
              </van-col>
              <van-col>
                <van-button v-show="row.ordererId == getInfo().userId" type="warning" size="mini" @click="showCancelOrderFn(row.id)">取消订单</van-button>
              </van-col>
            </van-row>
            <van-row style="margin-top:15px;"  @click="openChangeOrderWinFn(row)">
              <div style="border-top: 2px solid #b3b1f8; border-bottom: 2px solid #b3b1f8; font-size: 16px;font-weight: bold;">
                <van-swipe :autoplay="5000" :show-indicators="false">
                  <van-swipe-item v-for="detail in row.details" :key="detail.id">
                    <div :style="{display: 'flex', justifyContent: 'space-between', color: (detail.stepStatus == 1 ? '#c94949' : detail.stepStatus == 2 ? '#e78828' : detail.stepStatus == 3 ? '#41d249' : '#4d4d4d')}">
                      <span class="order-detail">{{detail.designNo}}</span>
                      <span class="order-detail">{{detail.color}}</span>
                      <span class="order-detail">匹:{{detail.num}}</span>
                      <span class="order-detail">米:{{detail.metre}}</span>
                    </div>
                  </van-swipe-item>
                </van-swipe>
                <span class="order-detail">交期: {{ row.deliveryAt }}</span>
              </div>
            </van-row>
            <van-row  @click="openChangeOrderWinFn(row)">
              <van-col>
                <span>特殊备注: </span>
              </van-col>
            </van-row>
            <van-row  @click="openChangeOrderWinFn(row)">
              <van-col :offset="2">
                <span>{{ row.specialRemark }}</span>
              </van-col>
            </van-row>
            <van-row type="flex" justify="space-between"  @click="openChangeOrderWinFn(row)">
              <div style="display: flex;margin-top:10px;">
<!--                <van-tag v-for="(tag,tagIndex) in row.tags" mark :key="tagIndex" :color="tag.color" >{{ tag.name }}</van-tag>-->
              </div>
              <van-col>
                <span>{{ row.ordererName }}</span>
              </van-col>
            </van-row>
            <van-row type="flex" justify="end"  @click="openChangeOrderWinFn(row)">
              <van-col>
                <span>{{ row.orderAt }}</span>
              </van-col>
            </van-row>
<!--            <van-row style="padding: 5px 10px; font-size: 16px; background: #dcdcdc;">
              <van-swipe :autoplay="6000" :show-indicators="false">
                <van-swipe-item v-for="task in row.operatingTasks" :key="task.id">
                  <div style="display: flex;justify-content: space-between">
                    <span v-show="task.executiveName == ''" :style="statusColorFn(task)" style="font-weight: bold;">部门: {{ task.depPostName }}</span>
                    <span v-show="task.executiveName != ''" :style="statusColorFn(task)" style="font-weight: bold;">执行人: {{ task.executiveName }}</span>
                    <span :style="statusColorFn(task)" style="font-weight: bold;">状态: {{ orderTaskStatusEnum(task.status) }}</span>
                    <span>指派人: {{ task.appointorName }}</span>
                  </div>
                  <div>
                    <span v-show="!task.acceptAt || task.acceptAt == ''">到达时间: {{ task.createAt }}</span>
                    <span v-show="task.acceptAt && task.acceptAt != ''">接单时间: {{ task.acceptAt }}</span>
                  </div>
                </van-swipe-item>
              </van-swipe>
            </van-row>-->
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <van-grid clickable :column-num="4" direction="horizontal" ref="clothOrderGridRef">
      <van-grid-item icon="home-o" text="全部单" @click="e => switchTabFn(0)" />
      <van-grid-item icon="completed" text="已完成" @click="switchTabFn(1)" />
      <van-grid-item icon="tosend" text="处理中" @click="switchTabFn(2)" />
      <van-grid-item icon="user-o" text="待接单" @click="switchTabFn(3)" />
    </van-grid>

    <van-dialog v-model="cancelOrderDialog.showCancelConfirm" title="" :showConfirmButton="true" :showCancelButton="true" :before-close="beforeCloseCancelOrderFn" @confirm="confirmCancelOrderFn" @cancel="cancelCancelOrderFn" >
      <template>
        <div style="display: flex;flex-flow: column; justify-content: center; align-items: center">
          <span style="padding:1vh 4vh;text-align: center;margin-top:2vh;color: #ea2121">
            取消之后将不能恢复,订单下所有任务都将删除.
          </span>
          <van-field style="padding:1vh 4vh" v-model="cancelOrderDialog.cancelRemark" type="textarea" label="取消备注:" label-align="right" placeholder="请输入取消原因" rows="3"></van-field>
        </div>
      </template>
    </van-dialog>
  </div>
</template>

<script>
import { openWin,comeBack } from "@/utils";
import dayjs from "dayjs";
import {loadClothOrder, orderUserStatusEnum, orderTaskStatusEnum, cancelOrder, loadDepConfig} from "@/api/order";
import {getInfo} from "@/utils/auth";
import {SPLIT_BLANK} from "@/api/enum";

export default {
  name: "clothOrder",
  data() {
    return {
      //数据列表
      listTimer: {},
      listRefreshing: true,
      listLoading: true,
      listFinished: false,
      queryParam: {
        beginAt: dayjs().subtract(1,"week").format('YYYY-MM-DD'),
        endAt: dayjs().add(1, "day").format('YYYY-MM-DD'),
        customerName: "",
        pageNum: 1,
        pageSize: 3,
        totalRow: 0,
        taskStatus: 0,
        orderByFlag: 0,
        status: 99,   //非取消全部
      },

      orderData: [],    //订单数据
      curTab: 3,    //默认最后一个标签

      //取消订单相关
      cancelOrderDialog: {
        showCancelConfirm: false,
        orderId: 0,
        cancelRemark: "",
      },

      /* 部门接单配置 */
      depConfig: [],
      /* 当前用户 */
      curUser: {
        id: 0,
        name: SPLIT_BLANK,
      }
    }
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      }
    }
  },
  methods: {
    comeBack,
    orderTaskStatusEnum,
    getInfo,

    //初始化
    initFn(that) {
      that.orderData.splice(0, that.orderData.length);
      that.switchTabFn(that.curTab);
      //必须延迟注册事件 不然数据会冲突
      setTimeout(() => {
        window.api.addEventListener({
          name:'viewappear'
        }, function() {
          // that.orderData.splice(0, that.orderData.length);
          // that.refreshOrderDataFn();
          // that.listClothOrderFn();
        });
      }, 2000);

      const tmpUser = getInfo();
      that.curUser.id = tmpUser.userId;
      that.curUser.name = tmpUser.realName;
      loadDepConfig({}, resData => {
        if(resData.code || resData.code == 0) {
          that.$toast.fail({
            message: resData.msg,
            onClose: () => {
              openWin("index");
            }
          });
          return;
        }
        resData.forEach(c => {
          that.depConfig.push(c);
        });
      });
    },

    //加载订单列表
    listClothOrderFn() {
      let that = this;
      that.listLoading = true;
      that.queryParam.designNo = that.queryParam.customerName;
      loadClothOrder(that.queryParam, resData => {
        if(resData.code || resData.code == 0) {
          that.$toast.fail(resData.msg);
          return;
        }
        resData.list.filter(order => order.status != 3 && order.status != 4).forEach(order => {
          // 下单人
          order.ownerFlag = order.ordererId == that.curUser.id;

          //当前用户
          order.details.forEach(subOrder => {
            let curSteps = subOrder.steps.filter(step => step.optId == that.curUser.id).sort((a,b) => a.status - b.status);
            if(curSteps && curSteps.length > 0) {
              subOrder.stepStatus = curSteps[0].status;
            }
          });


          that.orderData.push(order);

          //加当前用户任务标记
          /*order.tags = [];
          if(order.tasks.length == 0) {
            order.tags.push({
              "value": 1,
              "name": orderUserStatusEnum(1),
              "color": "#a9156f"
            });
          }
          order.tasks.forEach(task => {
            if(!task.userStatus) return;
            let tag = orderUserStatusEnum(task.userStatus);
            if(!order.tags.some(t => t.name == tag)) {
              order.tags.push({
                "value": task.userStatus,
                "name": tag,
                "color": task.userStatus == 1 ? "#a9156f" : task.userStatus == 2 ? "#a9740f" : task.userStatus == 3 ? "#06347a" : task.userStatus == 4 ? "#69048a" : task.userStatus == 5 ? "#830407" : task.userStatus == 6 ? "#fda7af" : ""
              });
            }
          });*/
        });

        //必须在视图更新后 list的placeHold.bottom更新后才能重置listLoading 在list里的load事件里再次判断listLoading=false才能加载下一页
        that.$nextTick(() => {
          that.listLoading = false;
          that.listRefreshing = false;
          if(resData.totalPage == that.queryParam.pageNum) {
            that.listFinished = true;
          }
        });
      });
    },

    //上拉加载下一页
    loadNextClothOrderDataFn() {
      let that = this;

      /*let vanList = that.$refs.vanList4OrderRef;    //湿检代码 因为这个load事件一直会触发
      let boundingClient = vanList.scroller.getBoundingClientRect()
      let placeholderRect = vanList.$refs.placeholder.getBoundingClientRect();
      console.log("---->2", placeholderRect.bottom, boundingClient.bottom);*/

      if(/*placeholderRect.bottom - boundingClient.bottom <= 0 && */!that.listLoading) {
        that.$toast.loading("加载中...");
        clearTimeout(that.listTimer);   //这个定时任务可以不要 为了显示效果好一点保留
        that.listTimer = setTimeout(() => {
          that.queryParam.pageNum++;
          that.listClothOrderFn();
        }, 1000);
      }
    },

    //打开详情
    openChangeOrderWinFn(row) {
      const that = this;
      if(!row) {
        row = {
          id: 0,
          ownerFlag: true
        }
      } else {
        row.ownerFlag = (row.ordererId == that.curUser.id);
      }
      openWin("cloth-order-change", {
        order: row
      });
    },

    //刷新订单数据
    refreshOrderDataFn() {
      let that = this;
      that.orderData.splice(0, that.orderData.length);
      that.listFinished = false;    //必须重置没有更多标记
      that.queryParam.pageNum = 1;

      that.listClothOrderFn();
    },

    //状态颜色
    statusColorFn(task) {
      if(task.status == 1) {
        return "color: #d90622"
      } else if(task.status == 2) {
        return "color: #FD7D1C"
      }
      return "";
    },

    //切换标签
    switchTabFn(curIndex) {
      let that = this;
      //添加样式 暂时没有其他好方法
      that.$refs.clothOrderGridRef.$el.childNodes.forEach((node, index) => {
        if(curIndex == index) {
          node.firstChild.childNodes.forEach(textNode => {
            textNode.style.color = "blue";
          });
        } else {
          node.firstChild.childNodes.forEach(textNode => {
            textNode.style.color = "";
          });
        }
      });

      that.queryParam.orderByFlag = curIndex;   //排序字段

      //加载数据
      that.queryParam.taskStatus = (curIndex == 0 ? 0 : (4 - curIndex));    //设置状态值
      that.refreshOrderDataFn();
    },

    //撤销订单
    showCancelOrderFn(id) {
      let that = this;
      that.cancelOrderDialog.orderId = id;
      that.cancelOrderDialog.showCancelConfirm = true;
    },
    confirmCancelOrderFn() {
      let that = this;
      if(that.cancelOrderDialog.cancelRemark == "") {
        that.$toast.fail("必须输入取消原因");
        return;   //return没用 得在beforeClose属性里阻止
      }
      cancelOrder({
        orderId: that.cancelOrderDialog.orderId,
        cancelRemark: that.cancelOrderDialog.cancelRemark,
      }, res => {
        that.$toast.success("取消订单成功");
        that.refreshOrderDataFn();
      });
    },
    cancelCancelOrderFn() {
      let that = this;
      that.cancelOrderDialog.orderId = 0;
      that.cancelOrderDialog.showCancelConfirm = false;
      that.cancelOrderDialog.cancelRemark = "";
    },
    beforeCloseCancelOrderFn(action, done) {
      let that = this;
      if (action === 'confirm' && that.cancelOrderDialog.cancelRemark == "") {
        done(false);
      } else {
        done();
      }
    }
  }
}
</script>

<style lang="scss">
.cloth-order {
  .van-search {
    z-index: 1;
  }
  .van-list {
    display: flex;
    flex-direction: column;
    align-items: center;
    .order-card {
      width: 96%;
      padding: 10px;
      background-color: white;
      margin-top: 15px;
      box-shadow: 5px 5px 5px #888888;
    }
    .van-col {
      margin-top: 10px;
    }
    .col-customer {
      font-size: 20px;
      color: #0c8aaf;
      font-weight: bold;
    }
    .order-detail {
      line-height: 30px;
      font-weight: bold;
      font-size: 16px;
    }
  }
}
</style>